﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using Umbraco.Web.Mvc;
using UmbracoExamine;
using UmbracoGuitarGreb.Models;

namespace UmbracoGuitarGreb.Controllers
{
    public class PublishSongController : SurfaceController
    {
        [ChildActionOnly]
        public ActionResult Publish()
        {
            var bands = Services.ContentService.GetContentOfContentType(GetContentType("Band").Id).Where(x => x.Published);

            var song = new PublishSong();

            song.Bands = bands;
            if (Members.GetCurrentMember() != null)
            {
                ViewBag.MemberName = Members.GetCurrentMember().Name;
                ViewBag.MemberId = Members.GetCurrentMember().Id;
            }
            return PartialView("SongForm", song);
        }

        [HttpPost]
        public ActionResult Publish(PublishSong song, string selectedBand)
        {
            if (!ModelState.IsValid)
            {
                return PartialView("SongForm", song);
            }

            var service = Services.ContentService;

            var band = Services.ContentService.GetContentOfContentType(GetContentType("Band").Id).Where(x => x.Published).FirstOrDefault(x => x.Name == selectedBand);


            if (band == null)
            {
                string letter = selectedBand.Substring(0, 1).ToLower();

                var alfabet = service.GetContentOfContentType(GetContentType("Alfabet").Id).Where(x => x.Published).FirstOrDefault(x => x.Name.ToLower().StartsWith(letter));

                band = service.CreateContent(selectedBand.ToFirstUpper(), alfabet, "Band");

                service.Save(band);
            }

            IContent newSong = service.CreateContent(song.Title.ToFirstUpper(), band, "Song");

            newSong.SetValue("bodyText", song.BodyText);
            newSong.SetValue("spotifyUri", song.SpotifyUri);
            if (Members.GetCurrentMember() != null)
            {
                newSong.SetValue("songMember", Members.GetCurrentMemberId());
            }

            service.Save(newSong);

            song = new PublishSong();

            song.Bands = AutocompleteBands();

            return Content("OK");
        }

        public IEnumerable<IContent> AutocompleteBands()
        {
            var bands = Services.ContentService.GetContentOfContentType(GetContentType("Band").Id);

            JavaScriptSerializer jss = new JavaScriptSerializer();

            string output = jss.Serialize(bands.OrderBy(x => x.Name));

            return bands;
        }

        private IContentType GetContentType(string alias)
        {
            return Services.ContentTypeService.GetContentType(alias);
        }
    }
}